const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    currentTab: 0,  // 当前选中的标签
    loading: false, // 加载状态
    hasMore: true,  // 是否还有更多数据
    page: 1,        // 当前页码
    activities: [], // 活动列表
    featuredActivities: [] // 精选活动
  },

  onLoad() {
    this.loadActivities();
    this.loadFeaturedActivities();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true
    }, () => {
      this.loadActivities(true).then(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadActivities();
    }
  },

  // 切换标签
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    if (tab === this.data.currentTab) return;
    
    this.setData({
      currentTab: tab,
      page: 1,
      activities: [],
      hasMore: true
    }, () => {
      this.loadActivities(true);
    });
  },

  // 加载活动列表
  async loadActivities(isRefresh = false) {
    try {
      this.setData({ loading: true });
      
      // 模拟接口请求
      const { page, currentTab } = this.data;
      const pageSize = 10;
      
      // 模拟网络请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 生成随机活动数据
      const newActivities = this.generateRandomActivities(page, currentTab, pageSize);
      
      this.setData({
        activities: isRefresh ? newActivities : [...this.data.activities, ...newActivities],
        hasMore: newActivities.length === pageSize,
        page: page + 1,
        loading: false
      });
      
    } catch (error) {
      console.error('加载活动列表失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    }
  },

  // 加载精选活动
  loadFeaturedActivities() {
    // 精选活动图片更换为更符合主题的图片
    const featuredImages = [
      'https://images.pexels.com/photos/2608517/pexels-photo-2608517.jpeg', // 音乐会
      'https://images.pexels.com/photos/7096/people-woman-coffee-meeting.jpg', // 讲座
      'https://images.pexels.com/photos/3755440/pexels-photo-3755440.jpeg', // 篮球
      'https://images.pexels.com/photos/6140931/pexels-photo-6140931.jpeg', // 社团
      'https://images.pexels.com/photos/6646918/pexels-photo-6646918.jpeg'  // 志愿服务
    ];
    
    const locations = ['西区艺术中心', '东区学术报告厅', '中心体育场', '学生活动中心', '图书馆'];
    
    for (let i = 0; i < 5; i++) {
      const date = new Date();
      date.setDate(date.getDate() + Math.floor(Math.random() * 10));
      
      this.data.featuredActivities.push({
        id: i + 1,
        title: `${['校园音乐节', '名师学术讲座', '校际篮球赛', '社团招新', '公益志愿行动'][i]}`,
        image: featuredImages[i],
        time: `${date.getMonth() + 1}月${date.getDate()}日 ${Math.floor(Math.random() * 12 + 9)}:00`,
        location: locations[i]
      });
    }
    
    this.setData({ featuredActivities: this.data.featuredActivities });
  },

  // 生成随机活动数据
  generateRandomActivities(page, tabIndex, pageSize) {
    const activities = [];
    
    // 不同类型活动的标签和颜色
    const activityTypes = [
      { tag: '全部', color: '#4b88ff' },
      { tag: '文艺', color: '#ff6b6b' },
      { tag: '学术', color: '#4ecdc4' },
      { tag: '体育', color: '#ff9f43' },
      { tag: '社团', color: '#a55eea' },
      { tag: '志愿', color: '#2ecc71' }
    ];
    
    // 预定义活动图片组
    const activityImages = [
      [
        'https://picsum.photos/seed/art1/800/500',
        'https://picsum.photos/seed/art2/800/500',
        'https://picsum.photos/seed/art3/800/500',
        'https://picsum.photos/seed/art4/800/500',
        'https://picsum.photos/seed/art5/800/500'
      ],
      [
        'https://picsum.photos/seed/academic1/800/500',
        'https://picsum.photos/seed/academic2/800/500',
        'https://picsum.photos/seed/academic3/800/500',
        'https://picsum.photos/seed/academic4/800/500',
        'https://picsum.photos/seed/academic5/800/500'
      ],
      [
        'https://picsum.photos/seed/sports1/800/500',
        'https://picsum.photos/seed/sports2/800/500',
        'https://picsum.photos/seed/sports3/800/500',
        'https://picsum.photos/seed/sports4/800/500',
        'https://picsum.photos/seed/sports5/800/500'
      ],
      [
        'https://picsum.photos/seed/club1/800/500',
        'https://picsum.photos/seed/club2/800/500',
        'https://picsum.photos/seed/club3/800/500',
        'https://picsum.photos/seed/club4/800/500',
        'https://picsum.photos/seed/club5/800/500'
      ],
      [
        'https://picsum.photos/seed/volunteer1/800/500',
        'https://picsum.photos/seed/volunteer2/800/500',
        'https://picsum.photos/seed/volunteer3/800/500',
        'https://picsum.photos/seed/volunteer4/800/500',
        'https://picsum.photos/seed/volunteer5/800/500'
      ],
    ];
    
    // 随机生成活动
    for (let i = 0; i < pageSize; i++) {
      // 如果是非全部标签，则只生成该类型的活动
      const typeIndex = tabIndex === 0 ? Math.floor(Math.random() * 5) + 1 : tabIndex;
      
      // 生成日期
      const date = new Date();
      date.setDate(date.getDate() + Math.floor(Math.random() * 30));
      const dateStr = `${date.getMonth() + 1}月${date.getDate()}日`;
      
      // 随机时间
      const hour = Math.floor(Math.random() * 12 + 8);
      const minute = Math.random() > 0.5 ? '00' : '30';
      const timeStr = `${hour}:${minute}`;
      
      // 随机图片 (使用不同类型的随机图片)
      const imageKeywords = ['concert', 'lecture', 'sports', 'club', 'volunteer'];
      const imageKeyword = imageKeywords[typeIndex - 1];
      
      // 随机参与人数
      const participants = Math.floor(Math.random() * 200) + 20;
      
      // 活动地点
      const locations = ['西区艺术中心', '东区学术报告厅', '中心体育场', '学生活动中心', '图书馆'];
      const location = locations[typeIndex - 1];
      
      // 活动主办方
      const organizers = ['学生会', '校团委', '体育部', '科技协会', '志愿者协会'];
      const organizer = organizers[typeIndex - 1];
      
      // 活动标题
      const titles = [
        ['校园歌手大赛', '话剧演出', '民族舞展演', '校园音乐节', '才艺大比拼'],
        ['学术讲座', '科技创新论坛', '读书沙龙', '考研经验分享会', '科普报告会'],
        ['校运会', '篮球联赛', '足球友谊赛', '羽毛球比赛', '乒乓球赛'],
        ['社团招新', '摄影展', '创业大赛', '辩论赛', '外语角活动'],
        ['环保活动', '社区服务', '爱心募捐', '支教活动', '关爱老人行动']
      ];
      
      const titleIndex = Math.floor(Math.random() * 5);
      const title = titles[typeIndex - 1][titleIndex];
      
      // 活动描述
      const descriptions = [
        '一场视听盛宴，展现校园青春活力，欢迎广大同学参与！',
        '邀请知名专家学者，共同探讨学术前沿，提升专业素养。',
        '以体育促健康，以竞技展风采，一场精彩的体育盛会！',
        '丰富校园文化生活，展示学生多彩才艺，欢迎踊跃参加！',
        '奉献爱心，传递温暖，践行社会责任，共建美好校园。'
      ];
      
      const id = (page - 1) * pageSize + i + 1;
      
      activities.push({
        id,
        title: `${title}`,
        description: descriptions[typeIndex - 1],
        image: activityImages[typeIndex - 1][titleIndex], // 使用预定义图片
        time: `${dateStr} ${timeStr}`,
        location,
        tag: activityTypes[typeIndex].tag,
        tagColor: activityTypes[typeIndex].color,
        organizer,
        organizerAvatar: '/images/avatar/default.png',
        participants
      });
    }
    
    return activities;
  },

  // 查看活动详情
  viewActivityDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/activity_detail/activity_detail?id=${id}`
    });
  },

  // 创建活动
  createActivity() {
    wx.navigateTo({
      url: '/pages/create_activity/create_activity'
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 搜索活动
  onSearch() {
    wx.showToast({
      title: '搜索功能开发中',
      icon: 'none'
    });
  }
})
